package com.cwj.thread;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.ExecutionException;

/**
 * @author wujie.chen
 * 2021/12/22 13:45
 */
public class Cancel {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new TestFrame("测试");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        });

    }
}

class TestFrame extends JFrame {
    private static final int FRAME_WIDTH = 530;
    private static final int FRAME_HEIGHT = 360;
    /*************View******************/
    private JPanel mainPanel = null;
    private JButton msgButton = null;
    private JLabel msgLabel = null;
    private JTextArea textArea;
    private JProgressBar progressBar;

    public TestFrame(String title) {
        super(title);
        initUI();
    }

    private void initUI() {
        //内容面板
        mainPanel = new JPanel();
        mainPanel.setPreferredSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
        this.setContentPane(mainPanel);
        //按钮
        msgButton = new JButton("'我是按钮'");
        // 监听者表示对按钮的点击事件感兴趣，于是注册到按钮上。
        msgButton.addActionListener(new ButtonClickListener());
        // msg显示文本
        msgLabel = new JLabel();
        // 将组建添加到窗体的内容面板中
        textArea = new JTextArea(50, 50);
        progressBar = new JProgressBar(0, 100);
        this.add(msgButton);
        this.add(msgLabel);
        this.add(textArea);
        this.add(progressBar);
        this.pack();
    }

    // /*监听者，实现了监听接口*/
    private class ButtonClickListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
//            msgLabel.setText("'你点击了按钮'");
            textArea.setText("");
            final int N = 10;
            PrimeNumbersTask task = new PrimeNumbersTask(textArea, N);
            task.addPropertyChangeListener(evt -> {
                if ("progress".equals(evt.getPropertyName())) {
                    progressBar.setValue((Integer)evt.getNewValue());
                }
            });
            task.execute();
//            try {
//                System.out.println(task.get()); //prints all prime numbers we have got
//            } catch (InterruptedException interruptedException) {
//                interruptedException.printStackTrace();
//            } catch (ExecutionException executionException) {
//                executionException.printStackTrace();
//            }
        }
    }
}

class PrimeNumbersTask extends
    SwingWorker<List<Integer>, Integer> {
    private static List<Integer> primeNumbers = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 27, 29, 31, 37, 41);
    private JTextArea textArea;
    private int numbersToFind;
    private boolean enough;
    private List<Integer> numbers;
    private Integer number;
    ListIterator<String> iterator;
    PrimeNumbersTask(JTextArea textArea, int numbersToFind) {
        //initialize
        this.enough = false;
        this.textArea = textArea;
        this.numbersToFind = numbersToFind;
        this.numbers = new ArrayList<>(numbersToFind);
        String text = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15";
        String[] split = text.split(",");
        List<String> strings = Arrays.asList(split);
        this.iterator = strings.listIterator();

    }

    @Override
    public List<Integer> doInBackground() {
        while (! enough && ! isCancelled()) {
            number = nextPrimeNumber();
            if(number != null){
                publish(number);
                setProgress(100 * numbers.size() / numbersToFind);
            }
            enough = numbers.size() >= numbersToFind;
        }
        return numbers;
    }

    @Override
    protected void process(List<Integer> chunks) {
        for (int number : chunks) {
            textArea.append(number + "\n");
        }
    }

    private Integer nextPrimeNumber(){
        while (iterator.hasNext()){
            Integer next = Integer.parseInt(iterator.next());
            if(isPrimeNumber(next)){
                return next;
            }
        }
        return null;
    }
    private boolean isPrimeNumber(int n){
        return primeNumbers.contains(n);
    }

}


